package com.zky.gulimall.cart.interceptor;

import com.zky.common.constant.AuthServerConstant;
import com.zky.common.constant.CartConstant;
import com.zky.common.vo.MemberRespVo;
import com.zky.gulimall.cart.vo.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * @Description 购物车拦截器   在执行目标方法之前判断用户登陆状态，并封装传给controller目标请求
 * @Author 张开源
 * @Date 2022/12/5 23:20
 * @Version 1.0
 **/
@Slf4j
public class CartInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UserInfo> threadLocal = new ThreadLocal<>();

    /**
     * 目标方法之前拦截
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        MemberRespVo memberRespVo = (MemberRespVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
        UserInfo userInfo = new UserInfo();
        if (memberRespVo != null) {
            //用户没登陆
            userInfo.setUserId(memberRespVo.getId());

        }
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if (CartConstant.TEMP_USER_COOKIE_NAME.equalsIgnoreCase(cookie.getName())) {
                    userInfo.setUserKey(cookie.getValue());
                    userInfo.setTempUser(true);
                }
            }
        }

        //首次如果未分配临时用户身份标识，则创建分配一个
        if (StringUtils.isEmpty(userInfo.getUserKey())) {
            log.warn("user-key is null,will to create new user-key");
            userInfo.setUserKey(UUID.randomUUID().toString());
        }

        //目标方法执行之前
        threadLocal.set(userInfo);
        return true;
    }

    /**
     * 业务执行之后，
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //此处若不判断是否是临时用户，则无限延长cookie过期时间
        if (!threadLocal.get().isTempUser()) {
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, threadLocal.get().getUserKey());
            cookie.setDomain("zky.com");
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
            response.addCookie(cookie);
        }
    }
}
